<template>
  <div class="blog-toc-container">
    <h2>目录</h2>
    <RightList :list="tocWithSelect" @select="handleClick"/>
  </div>
</template>

<script>
import RightList from "../RightList";
import {debounce} from "@/utils"
export default {
  name: "BlogToc",
  components: {
    RightList,
  },
  props: {
    toc: {
      type:Array,
      require: true,
    },
  },
  data(){
    return {
      activeAnchor:"" //目前激活的目录
    }
  },
  computed:{
       //根据目录计算出带select属性的目录
      tocWithSelect(){
        const getToc = (toc=[])=>{
          return toc.map((item)=>({
            ...item,
            isSelect:item.anchor === this.activeAnchor,
            children:getToc(item.children)
          }))
        }

        return getToc(this.toc);
      },

      //根据目录获取页面所有标题DOM
      doms(){
        const doms = [];

        const addToDoms = toc=>{
          for(const item of toc){
            const dom = document.getElementById(item.anchor);
            doms.push(dom);
            if(item.children&&item.children.length){
              addToDoms(item.children);
            }
          }
        }

        addToDoms(this.toc);
        return doms;
      }
  },
  created(){
    //监听mainScroll事件，事件触发调用this.setSelect函数
    this.setSelectDebounce = debounce(this.setSelect,50);
    this.$bus.$on("mainScroll",this.setSelectDebounce)
  },
  destroyed(){
    this.$bus.$off("mainScroll",this.setSelectDebounce)
  },
  methods:{
      //点击目录事件
      handleClick(item){
          location.hash = item.anchor;
      },

      //设置activeAnchor为正确的值
      setSelect(){
        const range = 200;//范围
        for(let dom of this.doms){
          if(!dom){
            continue;
          }
          const top = dom.getBoundingClientRect().top;//距离顶部的距离
          if(top>0&&top<range){
            //在规定范围内
            this.activeAnchor = dom.id;
            return;
          }else if(top>range){
            //在规定范围下方
            return;
          }else{
            //在规定范围上方
            this.activeAnchor = dom.id;//假设是激活的，在继续看后面的
          }
          
        }
      }
  }
};
</script>

<style scoped lang="less">
.blog-toc-container {
  width: 300px;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
  padding: 20px;
  h2 {
    font-weight: bold;
    letter-spacing: 2px;
    font-size: 1em;
    margin: 0;
  }
}
</style>